﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
using Toolkit.Web.Resources;

namespace Toolkit.Web.Helpers
{
    /// <summary>
    /// Helper for implementing and globalizing the jquery-ui datepicker control.
    ///
    /// Contains logic for converting .net supported date formats into jquery-ui datepicker formats:
    /// .NET    JQueryUI        Output      Comment
    /// --------------------------------------------------------------
    /// d       d               5           day of month (no leading zero)
    /// dd      dd              05          day of month (two digit)
    /// ddd     D               Thu         day short name
    /// dddd    DD              Thursday    day long name
    /// M       m               11          month of year (no leading zero)
    /// MM      mm              11          month of year (two digit)
    /// MMM     M               Nov         month name short
    /// MMMM    MM              November    month name long
    /// yy      y               09          year (two digit)
    /// yyyy    yy              2009        year (four digit)
    /// </summary>
    public static class JQueryUIDatePickerHelper
    {
        /// <summary>
        /// Converts the .net supported date format current culture format into jquery datepicker format.
        /// </summary>
        /// <returns>Format string that supported in jquery datepicker.</returns>
        public static string ConvertDateFormat()
        {
            return ConvertDateFormat(System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern);
        }

        /// <summary>
        /// Converts the .net supported date format current culture format into jquery datepicker format.
        /// </summary>
        /// <param name="format">Date format supported by .net.</param>
        /// <returns>Format string that supported in jquery datepicker.</returns>
        public static string ConvertDateFormat(string format)
        {
            string currentFormat = format;

            // Convert the date.
            currentFormat = currentFormat.Replace("dddd", "DD");
            currentFormat = currentFormat.Replace("ddd", "D");

            // Convert month.
            if (currentFormat.Contains("MMMM"))
            {
                currentFormat = currentFormat.Replace("MMMM", "MM");
            }
            else if (currentFormat.Contains("MMM"))
            {
                currentFormat = currentFormat.Replace("MMM", "M");
            }
            else if (currentFormat.Contains("MM"))
            {
                currentFormat = currentFormat.Replace("MM", "mm");
            }
            else
            {
                currentFormat = currentFormat.Replace("M", "m");
            }

            // Convert year.
            currentFormat = currentFormat.Contains("yyyy") ? currentFormat.Replace("yyyy", "yy") : currentFormat.Replace("yy", "y");

            return currentFormat;
        }

        /// <summary>
        /// Builds a script tag string in which applies localization for the jquery datepicker control.
        /// </summary>
        /// <returns>Html script tag as a string.</returns>
        public static string GetLocalizeScript()
        {
            StringBuilder script = new StringBuilder();
            CultureInfo culture = System.Threading.Thread.CurrentThread.CurrentCulture;

            script.Append(@"<script>");
            script.Append(@"jQuery(function($) {");

            script.AppendFormat(@"$.datepicker.regional['{0}'] = {{", culture.Name);

            script.AppendFormat(@"closeText: '{0}',", Language.Helpers_JQueryUIDatePickerHelper_Done);
            script.AppendFormat(@"prevText: '{0}',", Language.Helpers_JQueryUIDatePickerHelper_Prev);
            script.AppendFormat(@"nextText: '{0}',", Language.Helpers_JQueryUIDatePickerHelper_Next);
            script.AppendFormat(@"currentText: '{0}',", Language.Helpers_JQueryUIDatePickerHelper_Today);
            script.AppendFormat(@"weekHeader: '{0}',", Language.Helpers_JQueryUIDatePickerHelper_Wk);

            script.AppendFormat(@"monthNames: ['{0}'],", string.Join("','", culture.DateTimeFormat.MonthNames.Where(name => !string.IsNullOrEmpty(name)).ToArray()));
            script.AppendFormat(@"monthNamesShort: ['{0}'],", string.Join("','", culture.DateTimeFormat.AbbreviatedMonthNames.Where(name => !string.IsNullOrEmpty(name)).ToArray()));
            script.AppendFormat(@"dayNames: ['{0}'],", string.Join("','", culture.DateTimeFormat.DayNames.Where(name => !string.IsNullOrEmpty(name)).ToArray()));
            script.AppendFormat(@"dayNamesShort: ['{0}'],", string.Join("','", culture.DateTimeFormat.AbbreviatedDayNames.Where(name => !string.IsNullOrEmpty(name)).ToArray()));
            script.AppendFormat(@"dayNamesMin: ['{0}'],", string.Join("','", culture.DateTimeFormat.ShortestDayNames.Where(name => !string.IsNullOrEmpty(name)).ToArray()));
            script.AppendFormat(@"dateFormat: '{0}',", ConvertDateFormat());

            // The first day of the week, Sun = 0, Mon = 1, ...
            script.AppendFormat(@"firstDay: {0},", (int)culture.DateTimeFormat.FirstDayOfWeek);

            // True if right-to-left language, false if left-to-right.
            script.AppendFormat(@"isRTL: {0},", culture.TextInfo.IsRightToLeft.ToString().ToLower());

            string yearMonthPattern = culture.DateTimeFormat.YearMonthPattern;
            int monthIndex = yearMonthPattern.IndexOf("m", StringComparison.OrdinalIgnoreCase);
            int yearIndex = yearMonthPattern.IndexOf("y", StringComparison.OrdinalIgnoreCase);

            // Whether to show the month after the year in the header.
            script.AppendFormat(@"showMonthAfterYear: {0},", (monthIndex > yearIndex).ToString().ToLower());

            // Additional text to display after the year in the month headers.
            string yearSuffix = string.Empty;
            if (monthIndex < yearIndex)
            {
                yearSuffix = yearMonthPattern.Substring(yearIndex).Replace("y", string.Empty).Replace("Y", string.Empty).Replace("'", string.Empty).Trim();
            }
            else
            {
                yearSuffix = yearMonthPattern.Substring(0, monthIndex).Replace("y", string.Empty).Replace("Y", string.Empty).Replace("'", string.Empty).Trim();
            }
            script.AppendFormat(@"yearSuffix: '{0}'", yearSuffix);

            script.Append(@"};");

            script.AppendFormat(@"$.datepicker.setDefaults($.datepicker.regional['{0}']);", culture.Name);

            script.Append(@"});");
            script.Append(@"</script>");

            return script.ToString();
        }
    }
}
